import React, { useEffect } from "react";
import { Layout, Tree } from "antd";
import { Link, Routes, Route } from "react-router-dom";
import './App.css';
import { useSelector, useDispatch } from 'react-redux';
import { fetchComponents } from './features/componentInfos/componentInfosSlice';
import ComponentInfo from './ComponentInfo';
import Welcome from './Welcome';
import { parse, getDisplayName } from "../utils/reactComponentInfoUtils.js";
import { useState } from "react";
import { Input } from "antd";

export default function App() {
  const dispatch = useDispatch();
  const { components, loading, error } = useSelector(state => state.componentInfos);
  const [searchValue, setSearchValue] = useState('');

  useEffect(() => {
    dispatch(fetchComponents());
  }, [dispatch]);

  const getParentKey = (key, tree) => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (node.children.some(item => item.key === key)) {
          parentKey = node.key;
          return parentKey;
        }
        if (getParentKey(key, node.children)) {
          return getParentKey(key, node.children);
        }
      }
    }
    return parentKey;
  };

  const onSearch = (value) => {
    setSearchValue(value);
  };

  const filteredComponents = components.filter(comp => {
    const displayName = getDisplayName(parse(comp).jsDoc, parse(comp).name);
    return displayName.toLowerCase().includes(searchValue.toLowerCase());
  });

  const expandedKeys = filteredComponents.map(comp => comp.key);

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Layout.Header>
        Cookie!
      </Layout.Header>
      <Layout>
        <Layout.Sider width={300} style={{ overflow: 'auto' }}>
          <Input.Search
            placeholder="搜索组件"
            onChange={(e) => onSearch(e.target.value)}
            style={{ marginBottom: 8 }}
          />
          <Tree
            treeData={[{
              key: 'home',
              title: <Link to="/welcome">首页</Link>
            }, ...filteredComponents.map(comp => ({
              key: comp.key,
              title: <Link to={`/components/${comp.key}`}>{getDisplayName(parse(comp).jsDoc, parse(comp).name)}</Link>
            }))]}
            expandedKeys={expandedKeys}
            autoExpandParent={true}
          />
        </Layout.Sider>
        <Layout.Content>
          <Routes>
            <Route path="/welcome" element={<Welcome />} />
            <Route path="/components/:componentKey" element={<ComponentInfo />} />
          </Routes>
        </Layout.Content>
      </Layout>
    </Layout>
  );
}
